﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using System.Collections.Specialized;

namespace BlobExplorer
{
    /// <summary>
    /// Interaction logic for AddBlob.xaml
    /// </summary>
    public partial class AddBlob : Window
    {
        public string File
        {
            get { return (string)GetValue(FileProperty); }
            set { SetValue(FileProperty, value); }
        }

        // Using a DependencyProperty as the backing store for File.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FileProperty =
            DependencyProperty.Register("File", typeof(string), typeof(AddBlob));



        public string BlobName
        {
            get { return (string)GetValue(BlobNameProperty); }
            set { SetValue(BlobNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Name.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BlobNameProperty =
            DependencyProperty.Register("BlobName", typeof(string), typeof(AddBlob));

        public NameValueCollection Metadata { get; set; }

        public AddBlob()
        {
            InitializeComponent();
            Metadata = new NameValueCollection();

            DataContext = this;
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            GenerateMetadata();
            DialogResult = true;
        }

        private void GenerateMetadata()
        {
            string mdText = metadata.Text.Trim();

            if (!string.IsNullOrEmpty(mdText))
            {
                StringReader r = new StringReader(mdText);

                string item = null;
                while ((item = r.ReadLine()) != null)
                {
                    string key = item.Substring(0, item.IndexOf(':'));
                    string val = item.Substring(item.IndexOf(':') + 1);
                    Metadata.Add(key, val);
                }
            }
        }

        private void Browse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            bool? res = dlg.ShowDialog();

            if (res != null && res.Value)
            {
                File = dlg.FileName;
                if (string.IsNullOrEmpty(BlobName))
                {
                    BlobName = dlg.SafeFileName;
                }
            }
        }

    }
}
